var downloadFile = function(url) {
	var picname = url.substring(url.lastIndexOf("/") + 1);
	return new Promise((resolve) => {
		// console.log("开始下载：" + url)
		uni.downloadFile({
			url: url,
			success: (res) => {
				if (res.statusCode === 200) {
					// console.log("下载成功");
					uni.saveFile({
						tempFilePath: res.tempFilePath,
						success: function(rest) {
							// console.log("保存到本地：" + rest.savedFilePath);
							var imageCache = uni.getStorageSync('imageCache') || {};
							imageCache[picname] = rest.savedFilePath;
							uni.setStorageSync('imageCache', imageCache);
							// console.log(uni.getStorageSync('imageCache')[picname]);
							resolve(rest.savedFilePath);
						},
						fail: function(rest) {
							// console.log("保存到本地失败");
							resolve(url);
						}
					});
				} else {
					// console.log("下载失败");
					resolve(url);
				}
			},
			fail: (res) => {
				// console.log("下载失败");
				resolve(url);
			}
		});
	})
};
var isCache = function(url) {
	// console.log(url);
	// #ifdef H5
	return new Promise((resolve) => {
		resolve(url);
	});
	// #endif
	// #ifndef H5
	return new Promise((resolve) => {
		var picname = url.substring(url.lastIndexOf("/") + 1);
		var localPath = uni.getStorageSync('imageCache')[picname] || null;
		if (localPath) {
			uni.getFileInfo({
				filePath: localPath,
				success: function(res) {
					 // console.log("缓存图片存在"+localPath);
					resolve(localPath);
				},
				fail: function(res) {
					// console.log("缓存图片不存在");
					resolve(null);
				}
			});
		} else {
			resolve(null);
		}
	});
	// #endif
};
module.exports = {
	downloadFile: downloadFile,
	isCache: isCache
}
